package com.boil.qz.safekavass.shiro.filter;

import com.boil.util.Constants;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/**
 * Created by ChenYong on 2017-04-14.
 * <br>
 * 任意角色授权过滤器。 <br>
 * 即只要拥有某一个角色，则视为授权成功。<br>
 * 这个是扩展 Shiro，Shiro 本身只能是拥有所有角色才能授权成功。
 */
public class AnyRolesAuthorizationFilter extends RolesAuthorizationFilter {
    @Override
    public boolean isAccessAllowed(ServletRequest request, // 请求
                                   ServletResponse response, // 响应
                                   Object mappedValue) throws IOException {
        final Subject subject = getSubject(request, response);
        final String[] roles = (String[]) mappedValue;

        // 没有角色，允许访问
        if ((roles == null) || (roles.length == Constants.VALUE_0)) {
            return true;
        }

        // 只要拥有某一个角色，则视为授权成功
        for (String role : roles) {
            if (subject.hasRole(role)) {
                return true;
            }
        }

        return false;
    }
}